import {ref, computed, watchEffect} from 'vue'
import {http} from "api/axios.js";
import {ElMessage} from 'element-plus';
import {useRoute, useRouter} from "vue-router"

export function useEquipmentBuildsHall() {
    const classList = ref([{value: '青云'}, {value: '焚香'}, {value: '鬼王'}, {value: '合欢'}, {value: '灵汐'}])
    const selectedClass = ref('')
    const selectedSchool = ref('')
    const schoolList = computed(() => {
        if (!selectedClass.value) return []
        switch (selectedClass.value) {
            case '青云':
                return ['剑青云', '雷青云']
            case '焚香':
                return ['炎焚香', '咒焚香']
            case '鬼王':
                return ['煞鬼王', '罡鬼王']
            case '合欢':
                return ['影合欢', '月合欢']
            case '灵汐':
                return ['灵灵汐', '汐灵汐']
            default:
                return []
        }
    })

    const buildsList = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const loading = ref(false)

    const selectedBuild = ref()

    const filteredBuilds = computed(() => {
        return buildsList.value.filter(build => {
            const classMatch = !selectedClass.value || build.buildClass === selectedClass.value
            const schoolMatch = !selectedSchool.value || build.buildSchool === selectedSchool.value
            return classMatch && schoolMatch
        })
    })

    const paginatedBuilds = ref([])

    const updatePaginatedBuilds = () => {
        const start = (currentPage.value - 1) * pageSize.value
        const end = start + pageSize.value
        paginatedBuilds.value = filteredBuilds.value.slice(start, end)
    }

    const getClassTagType = (buildClass) => {
        const types = {
            '青云': 'primary',  // 蓝色系 #409EFF
            '焚香': 'danger',  // 红色系 #F56C6C
            '鬼王': 'dark',  // 黑色系 #303133
            '合欢': 'purple',  // 紫色系 #8A2BE2
            '灵汐': 'success'  // 绿色系 #67C23A
        }
        return types[buildClass] || 'info'
    }

    const handleLike = async (build) => {
        const user = JSON.parse(localStorage.getItem('user'))
        if (!user) {
            ElMessage.warning('请先登录后再点赞')
            return
        }

        http.post(`/api/equipment-builds/like/${build.id}?userId=${user.id}`).then(res => {
            console.log(res.data.data);
            if (res.data.data) {
                ElMessage.success("点赞成功")
                build.likeCountStatistics++
            } else {
                http.delete(`/api/equipment-builds/like/${build.id}?userId=${user.id}`).then(() => {
                    ElMessage.success("取消点赞成功")
                    build.likeCountStatistics--
                })
            }
        })
    }

    const getAllBuilds = async function () {
        loading.value = true
        try {
            const response = await http.get("/equipment/builds/recommend/all")
            buildsList.value = response.data.data.sort((a, b) => b.likeCountStatistics - a.likeCountStatistics)
        } catch (error) {
            console.error('获取配装列表失败:', error)
            buildsList.value = []
        } finally {
            loading.value = false
        }
    }

    const handleClassChange = () => {
        selectedSchool.value = ''
        currentPage.value = 1
    }

    const handleSchoolChange = () => {
        currentPage.value = 1
    }

    const handleSizeChange = (val) => {
        pageSize.value = val
        currentPage.value = 1
    }

    const handleCurrentChange = (val) => {
        currentPage.value = val
    }

    const router = useRouter()
    const handleViewDetail = (build) => {
        router.push({name: 'equipment_build_detail', query: {username: build.buildAuthor, id: build.id}})
    }
    getAllBuilds()

    watchEffect(() => {
        if (buildsList.value.length > 0) {
            updatePaginatedBuilds()
        }
    })

    return {
        classList,
        selectedClass,
        selectedSchool,
        schoolList,
        buildsList,
        currentPage,
        pageSize,
        filteredBuilds,
        paginatedBuilds,
        getClassTagType,
        handleClassChange,
        handleSchoolChange,
        handleSizeChange,
        handleCurrentChange,
        handleLike,
        handleViewDetail,
        loading,
    }
}